<?php
/*
 * This file is part of the BooXtore Student project.
 *
 * (c) Francis Backeland f.backeland@gmail.com
 * (c) Laurine Chaplot chaplot.laurine@orange.fr
 * (c) Julien Dutot julien.dutot@gmail.com
 * (c) Romain Guillaume romain-guillaume@orange.fr
 * (c) Guillaume Paringaux g.paringaux@gmail.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code
 * 
 */
namespace BXTR\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

/**
 * Globally used templates, used as subrequests.
 *
 * @see Controller
 */
class ViewController extends Controller 
{
    /**
     * Display the navigation bar
     *
     */
    public function linkListAction()
    {
        return $this->render('BXTRLayoutBundle:Front:Navigation.html.twig', array(
            'linklist' => $this->getLinkList(),
        ));
    }

    /**
     * Build the link list form the AdminBundle configuration
     *
     */
    private function getLinkList()
    {
        $linkList = [];
        $user = $this->getUser();
        $entities = $this->container->getParameter('bxtr_admin.entities');
        $categories = $this->container->getParameter('bxtr_admin.categories');

        // Append links to $linkList.
        // The order is defined by the configuration, it start with the order of the entities
        // then if an entity belong to a category, it add every entities of the category.
        $addedEntities = array();
        $categoriesCopy= $categories;
        foreach($entities as $entityName => $entityParameters) {
            // search for a matching category
            foreach($categoriesCopy as $k => $categoryDefinition) {
                $targetEntities = $categoryDefinition['entities'];
                if (in_array($entityName, $targetEntities)) {
                    $subList = array();
                    foreach($targetEntities as $targetName) {
                        $subList[] = array(
                            'path' => 'bxtr_admin_' . $targetName . '_list',
                            'name' => 'Ent.' . \ucfirst($targetName) . '.Link'
                        );
                        $addedEntities[] = $targetName;
                    }
                    $subArry = array('name' => $categoryDefinition['title'], 'sub' => $subList);
                    $linkList[] = $subArry;
                    array_splice($categoriesCopy, $k, 1);
                    break;
                }
            }
            if (!in_array($entityName, $addedEntities)) {
                $linkList[] = array(
                    'path' => 'bxtr_admin_' . $entityName . '_list',
                    'name' => 'Ent.' . \ucfirst($entityName) . '.link'
                );
            }
        }
        return $linkList;
    }
}
